﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameTimeSystem
{
    public class GameTimerManager: IGameTimerManager
    {
        Dictionary<int, List<GameTimer>> gameFixedUpdateTimers = new Dictionary<int, List<GameTimer>>();

        int[] updatePriority;

        Dictionary<int, List<GameTimer>> gameStaticUpdateTimers = new Dictionary<int, List<GameTimer>>();

        Dictionary<int, List<GameTimer>> gameDynamicUpdateTimers = new Dictionary<int, List<GameTimer>>();

        private Dictionary<int, List<GameTimer>>[] gameUpdateTimers;

        Dictionary<int, List<GameTimer>> gameLateUpdateTimers = new Dictionary<int, List<GameTimer>>();
        
        ObjPool<GameTimer> timerPool = new ObjPool<GameTimer>(50);

        public void Init()
        {
            updatePriority = new int[] { SystemPriority.Camera };
            gameUpdateTimers = new Dictionary<int, List<GameTimer>>[] { gameStaticUpdateTimers, gameDynamicUpdateTimers };
        }

        public GameTimer GetGameUpdateTimer(int priority,bool isStatic=false)
        {
            Dictionary<int, List<GameTimer>> timerDict;
            if (isStatic)
            {
                timerDict = gameStaticUpdateTimers;
            }
            else
            {
                timerDict = gameDynamicUpdateTimers;
            }

            GameTimer gameTimer = timerPool.GetObjFromPool();
            gameTimer.IsStatic = isStatic;
            if (!timerDict.ContainsKey(priority))
            {
                timerDict.Add(priority, new List<GameTimer>());
            }
            timerDict[priority].Add(gameTimer);
            gameTimer.SetOwner(timerDict[priority], timerPool);
            return gameTimer;
        }

        public void FixedUpdate(float deltaTime)
        {

        }

        public void Update(float deltaTime)
        {
            ForeachGameTimer(updatePriority, gameUpdateTimers, deltaTime);
        }

        public void LateUpdate(float deltaTime)
        {

        }

        private void ForeachGameTimer(int[] prioritys,Dictionary<int,List<GameTimer>>[] timersDicts,float deltaTime)
        {
            Dictionary<int, List<GameTimer>> timersDict;
            List<GameTimer> timers;
            for (int i = 0; i < prioritys.Length; i++)
            {
                for (int j = 0; j < timersDicts.Length; j++)
                {
                    timersDict = timersDicts[j];
                    if (timersDict.ContainsKey(prioritys[i]))
                    {
                        timers = timersDict[prioritys[i]];
                        for (int k = 0; k < timers.Count; k++)
                        {
                            timers[k].Polling(deltaTime);
                        }
                    }
                }
            }
        }

        public void SetSpeed(float speed, int targetSystem = -1)
        {
            throw new NotImplementedException();
        }
    }
}
